﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SP2013EventManager {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
                        
            Helpers.GetAllWebApplications(false);
            Helpers.FillWebAppComboBox(comboBox1);

            //listView1.AutoResizeColumn(1,ColumnHeaderAutoResizeStyle.ColumnContent);
        }

        // web apps change --> get site colls
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
            comboBox2.Items.Clear();
            comboBox3.Items.Clear();
            listBox1.Items.Clear();
            listBox2.Items.Clear();
            Cursor.Current = Cursors.WaitCursor;
            SPWebApplication selectedApp = (SPWebApplication)comboBox1.SelectedItem;

            foreach (SPWebApplication webApp in Helpers.webAppsList) {
                if (webApp == selectedApp) {
                    foreach (SPSite item in webApp.Sites) {
                        comboBox2.Items.Add(item.Url);
                    }
                    break;
                }
            }
        }

        // site colls change --> get sites
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) {
            comboBox3.Items.Clear();
            listBox1.Items.Clear();
            listBox2.Items.Clear();
            Cursor.Current = Cursors.WaitCursor;
            string selectedSiteColl = (string)comboBox2.SelectedItem;

            using (SPSite site = new SPSite(selectedSiteColl)) {
                SPWebCollection webColl = site.AllWebs;
                foreach (SPWeb web in webColl) {
                    comboBox3.Items.Add(web.Url);
                }
            }
        }

        // site change --> get lists
        SPWeb globalWeb = null;
        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e) {
            listBox1.Items.Clear();
            listBox2.Items.Clear();
            Cursor.Current = Cursors.WaitCursor;
            string siteUrl = (string)comboBox3.SelectedItem;

            using (SPSite site = new SPSite(siteUrl)) {
                using (SPWeb web = site.OpenWeb()) {
                    globalWeb = web;
                    SPListCollection listColl = web.Lists;

                    foreach (SPList list in listColl) {
                        listBox1.Items.Add(list.Title);
                    }
                }
            }
        }

        SPList selectedList = null;

        // list change --> get events
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
            listBox2.Items.Clear();
            Cursor.Current = Cursors.WaitCursor;
            string listName = (string)listBox1.SelectedItem;
            if (globalWeb != null) {
                selectedList = globalWeb.Lists[listName];
                listBox2.DisplayMember = "Type";

                foreach (SPEventReceiverDefinition item in selectedList.EventReceivers) {                    
                    listBox2.Items.Add(item);                    
                }
                
            }
        }

        SPEventReceiverDefinition selectedEvent = null;

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e) {
            listView1.Items.Clear();
            selectedEvent = (SPEventReceiverDefinition)listBox2.SelectedItem;
            Cursor.Current = Cursors.WaitCursor;

            if (selectedEvent != null) {
                listView1.Items.Add(new ListViewItem(new[] { "Id: ", selectedEvent.Id.ToString() }));
                listView1.Items.Add(new ListViewItem(new[] { "Name: ", selectedEvent.Name }));
                listView1.Items.Add(new ListViewItem(new[] { "Type: ", selectedEvent.Type.ToString() }));
                listView1.Items.Add(new ListViewItem(new[] { "Class: ", selectedEvent.Class }));
                listView1.Items.Add(new ListViewItem(new[] { "Assembly: ", selectedEvent.Assembly }));
                listView1.Items.Add(new ListViewItem(new[] { "SiteId: ", selectedEvent.SiteId.ToString() }));
                listView1.Items.Add(new ListViewItem(new[] { "WebId: ", selectedEvent.WebId.ToString() }));
                listView1.Items.Add(new ListViewItem(new[] { "Sequence: ", selectedEvent.SequenceNumber.ToString() }));
                listView1.Items.Add(new ListViewItem(new[] { "Url: ", selectedEvent.Url }));
            }
        }
        

        private void btnDelete_Click(object sender, EventArgs e) {
            if (selectedEvent != null) {
                var confirmResult = MessageBox.Show("Are you sure to delete this item ?", "Confirm Delete", MessageBoxButtons.YesNo);
                if (confirmResult == DialogResult.Yes) {
                    selectedEvent.Delete();
                    listBox2.Items.Remove(selectedEvent);
                    listView1.Items.Clear();
                }
            } else {
                MessageBox.Show("You need to select event receiver to delete!");
            }
        }

        private void btnAddNew_Click(object sender, EventArgs e) {
            if (selectedList != null) {

                SPEventReceiverType type;
                string selectedEvent = (string)comboBox5.SelectedItem;
                if (selectedEvent == "ItemAdded")
                    type = SPEventReceiverType.ItemAdded;
                else if (selectedEvent == "ItemAdding")
                    type = SPEventReceiverType.ItemAdding;
                else if (selectedEvent == "ItemUpdated")
                    type = SPEventReceiverType.ItemUpdated;
                else if (selectedEvent == "ItemUpdating")
                    type = SPEventReceiverType.ItemUpdating;
                else if (selectedEvent == "ItemAttachmentAdded")
                    type = SPEventReceiverType.ItemAttachmentAdded;
                else if (selectedEvent == "ItemAttachmentAdding")
                    type = SPEventReceiverType.ItemAttachmentAdding;
                else if (selectedEvent == "ItemAttachmentDeleted")
                    type = SPEventReceiverType.ItemAttachmentDeleted;
                else if (selectedEvent == "ItemAttachmentDeleting")
                    type = SPEventReceiverType.ItemAttachmentDeleting;
                else if (selectedEvent == "ItemDeleted")
                    type = SPEventReceiverType.ItemDeleted;
                else if (selectedEvent == "ItemDeleting")
                    type = SPEventReceiverType.ItemDeleting;
                else if (selectedEvent == "ItemCheckedIn")
                    type = SPEventReceiverType.ItemCheckedIn;
                else if (selectedEvent == "ItemCheckedOut")
                    type = SPEventReceiverType.ItemCheckedOut;
                else if (selectedEvent == "ItemCheckingIn")
                    type = SPEventReceiverType.ItemCheckingIn;
                else if (selectedEvent == "ItemCheckingOut")
                    type = SPEventReceiverType.ItemCheckingOut;
                else
                    type = SPEventReceiverType.ItemAdded;

                Helpers.EnsureEventReceiver(
                    selectedList, 
                    new[] { type }, 
                    textBox1.Text, 
                    textBox2.Text, 
                    SPEventReceiverSynchronization.Synchronous, 
                    10000);
            } else {
                MessageBox.Show("You need to select a list!");
            }

        }

        private void btnDeleteAll_Click(object sender, EventArgs e) {
            if (selectedList != null) {
                if (selectedList.EventReceivers.Count > 0) {
                    var confirmResult = MessageBox.Show("Are you sure to delete this item ?", "Confirm Delete", MessageBoxButtons.YesNo);
                    if (confirmResult == DialogResult.Yes) {
                        for (int i = 0; i < selectedList.EventReceivers.Count; i++) {
                            selectedList.EventReceivers[i].Delete();                            
                            listView1.Items.Clear();
                        }
                        listBox2.Items.Clear();
                    }
                } else {
                    MessageBox.Show("There are no event receivers on selected list!");
                }
            } else {
                MessageBox.Show("You need to select one list from which all event receivers will be deleted!");
            }
        }

        

        //TODO: open ddl file
        private void button2_Click(object sender, EventArgs e) {
            Stream myStream = null;
            comboBox4.Items.Clear();
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "All files (*.*)|*.*|assemblies (*.dll)|*.dll";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK) {
                try {
                    if ((myStream = openFileDialog1.OpenFile()) != null) {
                        using (myStream) {
                            textBox1.Text = openFileDialog1.FileName;
                            Assembly asm = Assembly.LoadFile(openFileDialog1.FileName);

                            foreach (Type type in asm.GetTypes()) {
                                comboBox4.Items.Add(type.Name);
                            }
                        }
                    }
                } catch (Exception ex) {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        
    }
}
